<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="12em">
      <el-form-item label="供应商" prop="supplier">
        <el-select-v2
          v-model="form.supplier"
          placeholder="选择供应商"
          :options="supplierStore.list"
          :props="{ value: 'id', label: 'name' }"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="输入优惠券名称" />
      </el-form-item>
      <el-form-item label="领取开始时间" prop="start_at">
        <el-date-picker
          v-model="form.start_at"
          type="datetime"
          placeholder="选择领取开始时间"
          value-format="YYYY-MM-DD HH:mm"
        />
      </el-form-item>
      <el-form-item label="领取结束时间" prop="end_at">
        <el-date-picker
          v-model="form.end_at"
          type="datetime"
          placeholder="选择领取结束时间"
          value-format="YYYY-MM-DD HH:mm"
        />
      </el-form-item>
      <el-form-item label="指定过期时间" prop="expired_at">
        <el-date-picker
          v-model="form.expired_at"
          type="datetime"
          placeholder="选择指定过期时间"
          value-format="YYYY-MM-DD HH:mm"
        />
      </el-form-item>
      <el-form-item label="领取多少天后有效" prop="valid_days">
        <el-input-number v-model="form.valid_days" :min="0" label="天数" />
      </el-form-item>
      <el-form-item label="每个用户最多领取数量" prop="usage_limit">
        <el-input-number v-model="form.usage_limit" :min="0" label="数量" />
      </el-form-item>
      <el-form-item label="发放数量" prop="total_limit">
        <el-input-number v-model="form.total_limit" :min="0" label="数量" />
      </el-form-item>
      <el-form-item label="剩余数量" prop="remaining_quantity">
        <el-input-number v-model="form.remaining_quantity" :min="0" label="数量" />
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input-number v-model="form.amount" :min="0" :precision="2" />
      </el-form-item>
      <el-form-item label="最低使用金额" prop="min_purchase">
        <el-input-number v-model="form.min_purchase" :min="0" :precision="2" />
      </el-form-item>
      <el-form-item label="是否启用" prop="is_active">
        <el-switch v-model="form.is_active" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          placeholder="请输入备注"
          type="textarea"
          :rows="5"
          resize="none"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        :loading="couponStore.loading.create || couponStore.loading.update"
        @click="handleSubmit"
      >
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { useCouponStore } from "@/store/modules/coupon/coupon";
import { useSupplierStoreHook } from "@/store/modules/supplier/supplier";
import type { FormInstance } from "element-plus";
import { CouponForm } from "@/api/coupon/coupon";
import { cloneDeep } from "lodash-es";

export type FormType = "add" | "edit";

const props = defineProps({
  modelValue: Boolean,
  type: {
    type: String as () => "add" | "edit",
    default: "add",
  },
  currentForm: {
    type: Object as () => Partial<CouponForm>,
    required: true,
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const title = computed(() => (props.type === "add" ? "添加优惠券" : "编辑优惠券"));

const couponStore = useCouponStore();
const supplierStore = useSupplierStoreHook();

const formRef = ref<FormInstance>();

const defaultForm: CouponForm = {
  supplier: "",
  is_active: true,
  name: "",
  amount: 0,
  min_purchase: 0,
  start_at: "",
  end_at: "",
  expired_at: "",
  valid_days: 0,
  usage_limit: 0,
  total_limit: 0,
  remaining_quantity: 0,
  remark: "",
};

const form = reactive<CouponForm>(cloneDeep(defaultForm));

const rules = {
  supplier: [{ required: true, message: "请选择供应商", trigger: "change" }],
  name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
  start_at: [{ required: true, message: "请选择领取开始时间", trigger: "change" }],
  end_at: [{ required: true, message: "请选择领取结束时间", trigger: "change" }],
  expired_at: [{ required: true, message: "请选择指定过期时间", trigger: "change" }],
  valid_days: [{ required: true, message: "请输入领取多少天后有效", trigger: "blur" }],
  total_limit: [{ required: true, message: "请输入发放数量", trigger: "blur" }],
  remaining_quantity: [{ required: true, message: "请输入剩余数量", trigger: "blur" }],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
  min_purchase: [{ required: true, message: "请输入最低使用金额", trigger: "blur" }],
  is_active: [{ required: true, message: "请选择是否启用", trigger: "change" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  usage_limit: [{ required: true, message: "请输入每个用户最多领取数量", trigger: "blur" }],
};

watch(visible, (val) => {
  if (val) {
    supplierStore.fetchList({ page: 1, size: 9999 });
    if (props.type == "edit") {
      Object.assign(form, props.currentForm);
    }
  } else {
    formRef.value?.resetFields();
    Object.assign(form, cloneDeep(defaultForm));
  }
});

async function handleSubmit() {
  try {
    await formRef.value?.validate();
    if (props.type === "add") {
      await couponStore.fetchCreate(form);
    } else {
      await couponStore.fetchUpdate(form);
    }
    emit("confirm");
    visible.value = false;
  } catch (e) {
    console.error(e);
  }
}
</script>
